package com.haiyou.common.util;

import com.haiyou.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;

@Slf4j
public class FileUtil {

    /**
     * 下载文件
     *
     * @param picUrl
     * @return
     */
    public static File download(String picUrl) {
        File file;
        try {
            URL httpUrl = new URL(picUrl);
            if (picUrl.toLowerCase().contains("png")) {
                file = new File(System.getProperty("user.dir") + "/downloads/" + IdWorker.getId() + ".png");
            } else {
                file = new File(System.getProperty("user.dir") + "/downloads/" + IdWorker.getId() + ".jpg");
            }
            FileUtils.copyURLToFile(httpUrl, file);

        } catch (IOException e) {
            e.printStackTrace();
            log.error("下载图片异常：{},{}", e.getMessage(), e);
            throw new BusinessException("下载图片异常");
        }
        return file;
    }

    /**
     * @param srcPath     原图片地址
     * @param desPath     目标图片地址
     * @param desFileSize 指定图片大小,单位kb
     * @param accuracy    精度,递归压缩的比率,建议小于0.9
     * @return
     */
    public static String compressPicForScale(String srcPath, String desPath,
                                             long desFileSize, double accuracy) {
        try {
            File srcFile = new File(srcPath);
            long srcFileSize = srcFile.length();
            log.info("原图片:{},大小:{}kb", srcPath, srcFileSize / 1024);
            //递归压缩,直到目标文件大小小于desFileSize
            compressPicCycle(desPath, desFileSize, accuracy);
            File desFile = new File(desPath);
            log.info("目标图片:{},大小:{}kb", desPath, desFile.length() / 1024);
            log.info("图片压缩完成!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return desPath;
    }

    public static void compressPicCycle(String desPath, long desFileSize, double accuracy) throws IOException {
        File imgFile = new File(desPath);
        long fileSize = imgFile.length();
        // 判断大小，如果小于指定大小，不压缩；如果大于等于指定大小，压缩
        if (fileSize <= desFileSize * 1024) {
            log.info("图片小于500k");
            return;
        }
        //计算宽高
        BufferedImage bim = ImageIO.read(imgFile);
        int imgWidth = bim.getWidth();
        int imgHeight = bim.getHeight();
        int desWidth = new BigDecimal(imgWidth).multiply(new BigDecimal(accuracy)).intValue();
        int desHeight = new BigDecimal(imgHeight).multiply(new BigDecimal(accuracy)).intValue();
        Thumbnails.of(desPath).size(desWidth, desHeight).outputQuality(accuracy).toFile(desPath);
        //如果不满足要求,递归直至满足小于1M的要求
        compressPicCycle(desPath, desFileSize, accuracy);
    }

}
